package com.muyu.system.service.impl;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.DanmoInformationBasic;
import com.muyu.remote.DanmoBasicService;
import com.muyu.system.domain.DanmoMarketCollect;
import com.muyu.system.domain.DanmoMarketProducts;
import com.muyu.system.mapper.DanmoMarketCollectMapper;
import com.muyu.system.mapper.DanmoMarketProductsMapper;
import com.muyu.system.req.DanmoUserShopReq;
import com.muyu.system.service.IDanmoMarketCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 书画市场收藏Service业务层处理
 * @author yangle
 * @date 2024-09-12
 */
@Service
public class DanmoMarketCollectServiceImpl implements IDanmoMarketCollectService
{
    @Autowired
    private DanmoMarketCollectMapper danmoMarketCollectMapper;

    @Autowired
    private DanmoMarketProductsMapper danmoMarketProductsMapper;


    /**
     * 查询书画市场收藏
     *
     * @param id 书画市场收藏主键
     * @return 书画市场收藏
     */
    @Override
    public DanmoMarketCollect selectDanmoMarketCollectById(Long id)
    {
        return danmoMarketCollectMapper.selectDanmoMarketCollectById(id);
    }

    /**
     * 查询书画市场收藏列表
     *
     * @param danmoMarketCollect 书画市场收藏
     * @return 书画市场收藏
     */
    @Override
    public List<DanmoMarketProducts> selectDanmoMarketCollectList(DanmoMarketCollect danmoMarketCollect)
    {
        Long userId = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        userId = loginUser.getUserid();
        System.out.println(userId);
        if (userId==null){
            return null;
        }
        danmoMarketCollect.setUserId(userId);
        List<DanmoMarketCollect> danmoMarketCollects = danmoMarketCollectMapper.selectDanmoMarketCollectList();
        Long[] ids = new Long[danmoMarketCollects.size()];
        for (int i = 0; i < danmoMarketCollects.size(); i++) {
            ids[i] = danmoMarketCollects.get(i).getProductId();
        }

        return danmoMarketProductsMapper.selectDanmoMarketProductsByIds(ids);
    }

    /**
     * 新增书画市场收藏
     *
     * @param danmoMarketCollect 书画市场收藏
     * @return 结果
     */
    @Override
    public Result insertDanmoMarketCollect(DanmoMarketCollect danmoMarketCollect)
    {
        //前端没带请求头稍等一下   看下数据库有没有数据
        //SecurityUtils securityUtils = new SecurityUtils();
        Long userId = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser==null){
            return Result.notLoggedIn("请登录");
        }
        userId = loginUser.getUserid();
        DanmoMarketCollect danmoMarketCollect1 = danmoMarketCollectMapper.selectDanmoMarketCollectByIdAndUserId(danmoMarketCollect.getProductId(),userId);
        if (danmoMarketCollect1 != null){
            return Result.success(1,"已收藏");
        }
        danmoMarketCollect.setUserId(userId);
        danmoMarketCollect.setCreateTime(DateUtils.getNowDate());
        danmoMarketCollect.setFavoriteTime(DateUtils.getNowDate());
        danmoMarketCollect.setIsActive(String.valueOf(true));
        danmoMarketCollectMapper.insertDanmoMarketCollect(danmoMarketCollect);
        return Result.success(1,"收藏成功");
    }

    /**
     * 修改书画市场收藏
     *
     * @param danmoMarketCollect 书画市场收藏
     * @return 结果
     */
    @Override
    public int updateDanmoMarketCollect(DanmoMarketCollect danmoMarketCollect)
    {
        danmoMarketCollect.setUpdateTime(DateUtils.getNowDate());
        return danmoMarketCollectMapper.updateDanmoMarketCollect(danmoMarketCollect);
    }

    /**
     * 批量删除书画市场收藏
     *
     * @param ids 需要删除的书画市场收藏主键
     * @return 结果
     */
    @Override
    public Result<Integer> deleteDanmoMarketCollectByIds(Long[] ids)
    {
        int i = danmoMarketCollectMapper.deleteDanmoMarketCollectByIds(ids);
        return Result.success(i,"删除成功");
    }

    /**
     * 删除书画市场收藏信息
     *
     * @param id 书画市场收藏主键
     * @return 结果
     */
    @Override
    public int deleteDanmoMarketCollectById(Long id)
    {
        return danmoMarketCollectMapper.deleteDanmoMarketCollectById(id);
    }

    /**
     * 取消收藏
     * @param danmoUserShopReq
     * @return
     */
    @Override
    public Result delCancelCollect(DanmoUserShopReq danmoUserShopReq) {
        Long userId = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        userId = loginUser.getUserid();
        System.out.println(userId);
        danmoUserShopReq.setUserId(userId);
        danmoMarketCollectMapper.delCancelCollect(danmoUserShopReq.getProductId(),userId);
        return Result.success("取消关注成功");
    }
   @Autowired
   private DanmoBasicService danmoBasicService;

    @Override
    public Result<List<DanmoMarketCollect>> myCollect(DanmoMarketCollect danmoMarketCollect) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoMarketCollect.setUserId(loginUser.getUserid());

        // 查询商品收藏列表
        List<DanmoMarketCollect> danmoMarketCollects = danmoMarketCollectMapper.selectCollectLists(danmoMarketCollect);

        if (danmoMarketCollects.isEmpty()){
            return Result.error("暂无收藏");
        }
        // 统计每个商品的收藏数量
        Map<Long, Integer> productCountMap = danmoMarketCollects.stream()
                .collect(Collectors.groupingBy(DanmoMarketCollect::getProductId, Collectors.summingInt(e -> 1)));

        // 提取所有商品 ID
        List<Long> productIds = new ArrayList<>(productCountMap.keySet());

        // 批量查询商品信息
        List<DanmoMarketProducts> danmoMarketProductsList = danmoMarketProductsMapper.selectDanmoMarketProductsIds(productIds);

        // 创建商品 ID 到商品对象的映射
        Map<Long, DanmoMarketProducts> productMap = danmoMarketProductsList.stream()
                .collect(Collectors.toMap(DanmoMarketProducts::getId, p -> p));

        // 为每个商品设置收藏数量
        for (Map.Entry<Long, Integer> entry : productCountMap.entrySet()) {
            Long productId = entry.getKey();
            Integer count = entry.getValue();
            DanmoMarketProducts product = productMap.get(productId);
            if (product != null) {
                product.setCollectionNumber(count);
            }
        }

        List<Long> longs = new ArrayList<>();
        for (DanmoMarketProducts danmoMarketProducts : danmoMarketProductsList) {
            longs.add(danmoMarketProducts.getUserId());
        }

        List<DanmoInformationBasic> danmoInformationBasicList = danmoBasicService.selectUserList(longs);
        for (DanmoInformationBasic danmoInformationBasic : danmoInformationBasicList) {
            for (DanmoMarketProducts danmoMarketProducts : danmoMarketProductsList) {
                if (danmoInformationBasic.getUserId().equals(danmoMarketProducts.getUserId())){
                    danmoMarketProducts.setDanmoInformationBasic(danmoInformationBasic);
                }
            }
        }

        return Result.success(danmoMarketCollects);
    }
}
